<template>
  <el-form ref="myform" :model="formItem" :rules="rules" label-width="auto" size="mini" class="mock-edit-form">
    <el-form-item label="模拟API" prop="api" required>
      <el-input v-model="formItem.api" placeholder="例：a/b/c/d" />
    </el-form-item>
    <el-form-item label="接口描述" prop="description" required>
      <el-input v-model="formItem.description" placeholder="接口描述" />
    </el-form-item>
    <el-form-item label="Json格式数据" prop="data" required>
      <el-input
        v-model="formItem.data"
        type="textarea"
        :rows="20"
        placeholder="{}"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import { create, update, detail } from '@neu/dcvm-ui/api/mock'

// 定义一个表单原始项
const formItem = {
  api: '',
  description: '',
  data: ''
}

export default {
  name: 'MocksEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    const validateJsonData = (rule, value, callback) => {
      try {
        JSON.parse(value)
        callback()
      } catch (err) {
        console.error(err)
        callback(new Error('无效的Json格式'))
      }
    }
    const validateApiPath = (rule, value, callback) => {
      if (/^\s*\//.test(value)) {
        callback(new Error('API不能以 / 开头'))
      } else {
        callback()
      }
    }
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        api: [
          { required: true, message: '模拟API不能为空', trigger: 'blur' },
          { validator: validateApiPath }
        ],
        description: [
          { required: true, message: '接口描述不能为空', trigger: 'blur' }
        ],
        data: [
          { required: true, message: 'Json格式数据不能为空', trigger: 'blur' },
          { validator: validateJsonData }
        ]
      }
    }
  },
  computed: {
    edited() {
      return this.id !== -1
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function(newVal, oldVal) {
      if (newVal > -1) {
        this.fetch()
      }
    }
  },
  created() {
    if (this.id > -1) {
      this.fetch()
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.edited
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>

<style lang="scss">

</style>
